package cn.dlc.com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @Author: dlc
 * @Date: 2021/11/26 - 11:27
 */
@Configuration
@EnableResourceServer
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 令牌解析服务器，远程解析（调用令牌认证服务）
     * @return
     */
    @Bean
    public ResourceServerTokenServices tokenServices(){
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        // 要检查的客户端
        services.setClientId("client_1");
        services.setClientSecret("secret");
        return services;
    }

    @Autowired
    private TokenStore tokenStore;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        // 指定资源id，之前在认证里面指定的id
        resources
                .resourceId("res_1")
                // 指定验证令牌的服务
                //  .tokenServices(tokenServices())
                .tokenStore(tokenStore)
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                // 这个是用来校验“客户端”是否有访问的权限的
                .antMatchers("/**").access("#oauth2.hasScope('all')")
                .anyRequest().authenticated();

                // 允许跨域，应该主要针对简化模式的情况
                /*.and()
                .headers().addHeaderWriter((request,response) -> {
                    // 允许跨域，允许其他的客户端系统来访问
                    response.addHeader("Access-Control-Allow-Origin","*");
                    // 判断是不是预检请求
                    if(request.getMethod().equals("OPTIONS")) {
                        response.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"));
                        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
                    }
                });*/
    }
}
